package com.coocaa.x.service.litewebserver.webserver;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.service.litewebserver.webserver.aidl.ILiteWebServerService;

import java.io.IOException;

public class LiteWebServerService extends Service {
    private Context mContext = this;
    private static class WebServerStub extends ILiteWebServerService.Stub {
        private LiteWebHttpd httpd = null;

        public WebServerStub(Context mContext) {
            httpd = new LiteWebHttpd(mContext, 40123);
        }

        @Override
        public boolean isStarted() throws RemoteException {
            return httpd.isAlive();
        }

        @Override
        public int start() throws RemoteException {
            if (!Android.isNetConnected(CoocaaApplication.getContext()))
                return -1;
            try {
                httpd.start();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return 0;
        }

        @Override
        public int stop() throws RemoteException {
            if (!Android.isNetConnected(CoocaaApplication.getContext()))
                return -1;
            httpd.stop();
            return 0;
        }


        @Override
        public String getURL() throws RemoteException {
            if (!Android.isNetConnected(CoocaaApplication.getContext()))
                return "";
            return httpd.getURL();
        }
    }

    private WebServerStub stub = null;

    @Override
    public void onCreate() {
        super.onCreate();
        stub = new WebServerStub(mContext);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return stub;
    }
}
